var maxCount = 8;
var counter = 0;
var url = $("#imgUploadPath").val();
var imgDownPath =  $("#imgDownPath").val();
var dataContent = {};
$(document).ready(function() {
	// Change this to the location of your server-side upload handler:
		'use strict';
			var uploadButton = $('<button/>').addClass('btn btn-primary').prop(
				'disabled', true).on('click', function() {
				var $this = $(this), data = $this.data();
				var span = $this.prev().prev();
				var spanV = $.trim($(span).html()); // 图片名称
				var imgId = ""; // 图片id
				if (document.getElementById(spanV)) {
					imgId = $(document.getElementById(spanV)).val();
				} else {
					imgId = spanV;
				}
				deleteImg(imgId, spanV, $this);

				/*
				 * $this .off('click') .text('Abort') .on('click', function () {
				 * $this.remove(); data.abort(); });
				 * data.submit().always(function () { $this.remove(); });
				 */
			});
		$('#fileupload').fileupload(
				{
					url : url,
					autoUpload : true,
					acceptFileTypes : /(\.|\/)(gif|jpe?g|png)$/i,
					maxFileSize : 1000000, // 1M
					// Enable image resizing, except for Android and Opera,
					// which actually support image resizing, but fail to
					// send Blob objects via XHR requests:
					disableImageResize : /Android(?!.*Chrome)|Opera/
							.test(window.navigator.userAgent),
					previewMaxWidth : 100,
					previewMaxHeight : 100,
					previewCrop : true
				}).on(
				'fileuploadadd',
				function(e, data) {
					var fileCount = data.files.length;
					var count = $("#uploadCount").val();
					if (typeof (count) != "undefined") {
						maxCount = count;
					}
					if (counter >= maxCount) {
						layer.msg("上传图片不能超过" + maxCount + "张！");
						return false;
					}
					counter++;
					data.context = $('<div style="float:left;margin-left:10px;"/>').appendTo('#files');
					$.each(data.files, function(index, file) {
						var node = $('<p class="img_no_select" onclick="selectImg(\'\',this)"/>').append(
								$('<span style="display:none;"/>').text(
										file.name));
						/*if (!index) {
							node.append('<br>').append(
									uploadButton.clone(true).data(data));
						}*/
						node.appendTo(data.context);
						var fname= file.name;
                        dataContent[fname] =data.context;
                        var data1 = dataContent;
                        var data2 = dataContent;
					});

				}).on('fileuploadprocessalways',function(e, data) {
                    var index = data.index,
                        file = data.files[index],
                        node = $(data.context.children()[index]);
                    if (file.preview) {
                        node.prepend(file.preview);
                    }
                    if (file.error) {
                        node
                            .append('<br>')
                            .append($('<span class="text-danger"/>').text(file.error));
                    }
                    /*
					var index = data.index, file = data.files[index];
					if (typeof (data.context) == "undefined") {
						return;
					}
					var node = $(data.context.children()[index]);
					if (file.preview) {
						node.prepend('<br>').prepend(file.preview);
					}
					if (file.error) {
						node.append('<br>').append(
								$('<span class="text-danger"/>').text(
										file.error));
					}*/
					/*if (index + 1 === data.files.length) {
						data.context.find('button').text('删除').prop('disabled',
								!!data.files.error);
					}*/
				}).on('fileuploaddone',function(e, data) {
                    var data1 = dataContent;
                    $.each(data.result, function (index, file) {
                        var fname = file.name;
                        if (file.id) {
                            var obj = $(dataContent[fname].children()[index]);
                            var inputHtml=$('<input type="hidden" id="' + file.id
                                + '" value="' + file.id
                                + '" name="img_name"/>');
                            obj.attr("id",file.id);
                            obj.append(inputHtml);
                            //obj.bind('click',selectImg(file.id,obj));
                        } else if (file.error) {
                            var error = $('<span class="text-danger"/>').text(file.error);
                            $(dataContent[fname].children()[index])
                                .append('<br>')
                                .append(error);
                        }
                    });

                    processImg();
				}).on(
				'fileuploadfail',
				function(e, data) {
					$.each(data.files, function(index) {
						var error = $('<span class="text-danger"/>').text(
								'File upload failed.');
						$(data.context.children()[index]).append('<br>')
								.append(error);
					});
				}).prop('disabled', !$.support.fileInput).parent().addClass(
				$.support.fileInput ? undefined : 'disabled');
	});
function processImg(){
    var imgIds = "";
    var i = 0;
    $("input[name=img_name]").each(function(){
        if(i == 0){
            imgIds = $(this).val()
        }else{
            imgIds =imgIds + "," + $(this).val()
        }
        i++;
    });
    $("#images").val(imgIds);
}

function loadImg(imgIds) {
	if ($.trim(imgIds) == "") {
		return;	
	}
	var idArr = imgIds.split(",");
	var html = '<div style="float:left;margin-left:10px;"><p id="imgId" class="img_no_select" onclick="selectImg(\'imgId\',this)"><img  src="imgUrl" width="100px" height="100px"><br><span style="display:none;">imgName</span></p></div>';
	var parentlEle = $("#files");
    parentlEle.html("");
	var imgPath = $("#imgDownPath").val();
	for ( var i = 0; i < idArr.length; i++) {
		counter++;
		var path = imgPath + idArr[i];
		var sonHtml = html.replace("imgUrl", path).replace("imgUrl", path).replace("imgId", idArr[i]).replace("imgId", idArr[i]).replace("imgName", idArr[i])
				.replace("imgName", idArr[i]).replace("imgName", idArr[i]);
		parentlEle.append(sonHtml);
		
		var inputHtml='<input type="hidden" id="' + idArr[i]
		+ '" value="' + idArr[i]
		+ '" name="img_name"/>';
		parentlEle.append(inputHtml);
	}
}
function selectImg(imgId,obj){
    if (typeof($(obj).attr("select")) != "undefined") {
        $(obj).removeClass("img_select");
        $(obj).addClass("img_no_select");
        $(obj).removeAttr("select");
    } else {
        $(obj).removeClass("img_no_select");
        $(obj).addClass("img_select");
        $(obj).attr("select", "true");
    }
}

function deleteImg(imgId, imgName, btn) {
    var url = $("#imgDelPath").val() + imgId;
    $.ajax({
        type: "POST",
        url: url,
        data: {
            imgId: imgId
        },
        success: function (data) {
            layer.close('ts');
            if (data.code == 1) {
                //layer.msg("删除成功！");
                if (typeof (document.getElementById(imgName)) != "undefined") {
                    $(document.getElementById(imgName)).remove();
                }
                $(btn).parent().parent().remove();
                counter--;
                alert("删除成功");
            } else {
                alert("删除失败");
                layer.msg(dataArr.msg);
            }
        }
    });
}

    function deleteImg_(imgId) {
        var url = $("#imgDelPath").val();
        $.ajax({
            type : "POST",
            url : url,
            data:{
                imgId:imgId
            },
            success : function(data) {
                $(".img_select").remove();
                counter--;
                layer.msg("删除成功");
            },
            error: function(data){
                layer.msg("删除失败");
            }
        });
    }

